package com.helper;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * 类转化器
 * @param <T> 要转化的类型
 */

public class BeanGenerator<T> {

    /*
     * 获取所有的属性名
     */
    private String[] getPropertyNames(Class<T> cls){
        //获取所有的属性名
        Field[] declaredFields = cls.getDeclaredFields();
        String[] names = new String[declaredFields.length];
        for (int i = 0;i<declaredFields.length;i++){
            names[i]=declaredFields[i].getName();
        }
        return names;
    }
     public T generateBean(Class<T> cls,Object[] obj){
         String[] names = getPropertyNames(cls);
         T bean = null;
         try {
             //创建对象
             bean = cls.newInstance();
             for (int i = 0; i < names.length; i++) {
                 try {
                     BeanUtils.setProperty(bean,names[i],obj[i]);
                 } catch (InvocationTargetException e) {
                     e.printStackTrace();
                 }
             }
         } catch (InstantiationException e) {
             e.printStackTrace();
         } catch (IllegalAccessException e) {
             e.printStackTrace();
         }

         return bean;
     }
}
